package m.jclecai.com.fragment;


import android.Manifest;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.app.AlertDialog;
import android.text.Html;
import android.text.TextUtils;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.gongwen.marqueen.MarqueeView;
import com.squareup.okhttp.Request;
import com.tbruyelle.rxpermissions.RxPermissions;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import m.jclecai.com.R;
import m.jclecai.com.activity.ChampionActivity;
import m.jclecai.com.activity.EventActivity;
import m.jclecai.com.activity.LotteryBJDCActivity;
import m.jclecai.com.activity.LotteryInfoActivity;
import m.jclecai.com.activity.LotteryJCLQActivity;
import m.jclecai.com.activity.LotteryJCZQActivity;
import m.jclecai.com.activity.LotteryKLPKActivity;
import m.jclecai.com.activity.LotteryLuckyActivity;
import m.jclecai.com.activity.LuckyWalkActivity;
import m.jclecai.com.activity.SignActivity;
import m.jclecai.com.activity.TaskActivity;
import m.jclecai.com.adapter.BannerAdapter;
import m.jclecai.com.base.BaseFragment;
import m.jclecai.com.bean.AdvertBean;
import m.jclecai.com.bean.HomeItem;
import m.jclecai.com.bean.RecordsBean;
import m.jclecai.com.bean.UserBean;
import m.jclecai.com.bean.VersionBean;
import m.jclecai.com.constant.Constant_Url;
import m.jclecai.com.listener.Callback;
import m.jclecai.com.service.DownloadService;
import m.jclecai.com.ui.BetKSActivity;
import m.jclecai.com.ui.BetPlS_PLW_SD_QXCActivity;
import m.jclecai.com.ui.BetRXJ_SFCActivity;
import m.jclecai.com.ui.BetSEXWActivity;
import m.jclecai.com.ui.BetSSCActivity;
import m.jclecai.com.ui.BetSSQ_DLT_QLCActivity;
import m.jclecai.com.ui.BetSYXWActivity;
import m.jclecai.com.ui.BettingKLSFActivity;
import m.jclecai.com.utils.BaseUtils;
import m.jclecai.com.utils.ChannelUtil;
import m.jclecai.com.utils.MyLog;
import m.jclecai.com.utils.MyToast;
import m.jclecai.com.utils.PreferenceUtil;
import m.jclecai.com.utils.http.FastOk;
import m.jclecai.com.utils.http.HttpManager;
import m.jclecai.com.view.AutoSwipeRefreshLayout;
import m.jclecai.com.view.CircleFlowIndicator;
import m.jclecai.com.view.ExGridView;
import m.jclecai.com.view.NoticeMFView;
import m.jclecai.com.view.ViewFlow;
import rx.functions.Action1;

import static m.jclecai.com.utils.http.SystemUtils.getVersionName;


/**
 * 购彩页面
 */
public class HomeFragment extends BaseFragment implements View.OnClickListener {


    private List<AdvertBean> listData = new ArrayList<>();

    List<HomeItem> mMenu;
    @BindView(R.id.sr_refresh)
    AutoSwipeRefreshLayout sr_refresh;
    @BindView(R.id.gv)
    ExGridView gv;
    @BindView(R.id.aoto_view)
    LinearLayout aoto_view;
    @BindView(R.id.viewflow)
    ViewFlow viewflow;
    @BindView(R.id.viewflowindic)
    CircleFlowIndicator viewflowindic;
    @BindView(R.id.marqueeView)
    MarqueeView marqueeView;
    @BindView(R.id.ll_marqueeView)
    LinearLayout ll_marqueeView;

    //==banner下面的四个按钮==
    @BindView(R.id.ll_sign)
    LinearLayout mLlSign;
    @BindView(R.id.ll_lottery)
    LinearLayout mLlLottery;
    @BindView(R.id.ll_task)
    LinearLayout mLlTask;
    @BindView(R.id.ll_activity)
    LinearLayout mLlActivity;

    @Override
    public int getLayoutId() {
        return R.layout.fragment_buy_lottery;
    }

    @Override
    public void initView() {
        setTitle("首页");
        rightOptionText("开奖信息");

        sr_refresh.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                getBannerData();
                showMarpuee();
                getLottery();
            }
        });

        gv.setCallback(new Callback<HomeItem>() {
            @Override
            public void onItemClick(final HomeItem item) {
                super.onItemClick(item);
                if ("0".equals(item.getStatus())) {
                    startAction(item.getTypes());
                } else {
                    //这里我们要做的一个操作就是弹出对话框提示暂停销售；
                    AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
                    builder.setTitle("提示");
                    builder.setMessage("该彩种暂停销售!!！");
                    builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            dialog.dismiss();
                            startAction(item.getTypes());
                        }
                    });
                    builder.show();
                }
            }

            @Override
            public void onClickSetChangedText() {
                super.onClickSetChangedText();
                MyToast.showToast(getActivity(), "复制成功");
                String s = PreferenceUtil.readString(getActivity(), PreferenceUtil.WEXIN, "");
                BaseUtils.setClipString(getActivity(), PreferenceUtil.readString(getActivity(), PreferenceUtil.WEXIN, ""));
                BaseUtils.startWeChat(getActivity());
            }

            @Override
            public void callbackSuccess() {
                super.callbackSuccess();
                //放在这里请求，防止出现空指针；
                getWeChat();
            }
        });
        ll_marqueeView.setVisibility(View.GONE);
        mMenu = new ArrayList<>();

        getBannerData();

        showMarpuee();

        getLottery();

        String date = PreferenceUtil.readString(getActivity(), "date", "");
        checkVersion();
        //这里我们要做的一个操作就是，一天的第一次进入app的时候，我们才提示更新，
//        if (!getTodayDate().equals(date)) {
//            checkVersion();
//        }
    }

    /**
     * 获取当前日期的String
     *
     * @return
     */
    public String getTodayDate() {
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyMMdd");
        String todayDate = simpleDateFormat.format(new Date());
        return todayDate;
    }

    /**
     * 请求服务器，来检查本地的版本和服务器是否一样；
     */
    private void checkVersion() {
        //1、获取本地版本信息；
        //2、请求服务器是否更新；
        //3、弹出对话框显示新版本特性；
        //4、启动Services;

        final SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyMMdd");

        PreferenceUtil.writeString(getActivity(), "date", simpleDateFormat.format(new Date()));

        final String versionCode = getVersionCode();
        final String versionName = getVersionName();

        final AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());

        final View view = View.inflate(getActivity(), R.layout.dialog_update_layout, null);
        builder.setView(view);


        HttpManager.getAsyn(Constant_Url.GET_LATEST + "?version=" + versionName + "&type=android" + "&versionCode=" + versionCode+"&appstore="+ ChannelUtil.getChannel(), new HttpManager.StringCallback() {
            @Override
            public void onFailure(Request request, IOException e) {
                //请检查网络；
                DisPlay("请检查网络...");
            }

            @Override
            public void onResponse(String response) {


                if (!TextUtils.isEmpty(response)) {

                    //判断返回结果：
                    final VersionBean versionBean = FastOk.get(response, VersionBean.class);
                    //builder.show();
                    if (versionBean != null) {

                        if (versionBean.getStatus().equals("1")) {
                            try {
                                final AlertDialog alertDialog = builder.create();

                                RxPermissions rxPermissions = new RxPermissions(getActivity());
                                rxPermissions.request(Manifest.permission.WRITE_EXTERNAL_STORAGE)
                                        .subscribe(new Action1<Boolean>() {
                                            @Override
                                            public void call(Boolean aBoolean) {
                                                if (aBoolean) {
                                                    alertDialog.show();
                                                } else {
                                                    DisPlay("获取权限失败！！！");
                                                }
                                            }
                                        });


                                view.findViewById(R.id.tv_update).setOnClickListener(new View.OnClickListener() {
                                    @Override
                                    public void onClick(View v) {
                                        //这里我们要做的一个操作就是升级；
                                        Intent intent = new Intent(getActivity(), DownloadService.class);

                                        long apkSize = 0;

                                        try {
                                            //服务器没有找到数据就会报异常
                                            apkSize = Long.parseLong(versionBean.getApkSize());
                                        } catch (NumberFormatException e) {
                                            e.printStackTrace();
                                        }
                                        intent.putExtra(DownloadService.APK_SIZE, apkSize);
                                        intent.putExtra(DownloadService.DOWNLOAD_URL, versionBean.getDownload());
                                        getActivity().startService(intent);
                                        alertDialog.dismiss();
                                    }
                                });
                                //这里表示需要更新；在这里写的话可以偷懒
                                view.findViewById(R.id.tv_no_update).setOnClickListener(new View.OnClickListener() {
                                    @Override
                                    public void onClick(View v) {
                                        alertDialog.dismiss();
                                    }
                                });

                                String content = "版本:" + versionBean.getVersion() + "\n";

                                float v = Float.parseFloat(versionBean.getApkSize()) / 1024 / 1024;
                                //保留两位小数
                                content += "包大小:" + (float) (Math.round(v * 100)) / 100 + "m\n\n";


                                String[] split = versionBean.getContent().split(";");
                                content += "更新内容：\n";
                                for (int i = 0; i < split.length; i++) {
                                    content += split[i] + "。\n";
                                }
                                content += "升级的小伙伴,今天晚上更容易中大奖哦。";
                                ((TextView) view.findViewById(R.id.tv_content)).setText(content);
                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                        }

                    }
                }
            }
        });

    }


    /**
     * 这里我们获取版本号；
     *
     * @return
     */
    private String getVersionCode() {

        PackageManager packageManager = getActivity().getPackageManager();
        try {
            PackageInfo packageInfo = packageManager.getPackageInfo(getActivity().getPackageName(), 0);
            int versionCode = packageInfo.versionCode;
            return versionCode + "";
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }

        return "";
    }

    void showMarpuee() {
        HttpManager.getAsyn(Constant_Url.MARQUEE, new HttpManager.StringCallback() {
            @Override
            public void onFailure(Request request, IOException e) {
                //bugly后台发现报错；
                if (ll_marqueeView != null) {
                    ll_marqueeView.setVisibility(View.GONE);
                }
                DisPlay("网络异常！");
            }

            @Override
            public void onResponse(String response) {
                if (!TextUtils.isEmpty(response)) {
                    JSONObject parse = FastOk.get(response, JSONObject.class);
                    if (parse != null) {

                        if ("0".equals(parse.getString("status"))) {
                            JSONArray records = parse.getJSONArray("records");
                            List<CharSequence> info = new ArrayList<>();
                            for (int i = 0; i < records.size(); i++) {

                                info.add(formatStr(records.getJSONObject(i).getString("title")));

                            }
                            if (info.size() > 0 && ll_marqueeView != null)
                                ll_marqueeView.setVisibility(View.VISIBLE);
                            if (marqueeView != null) {
                                NoticeMFView noticeMFView = new NoticeMFView(getActivity());
                                noticeMFView.setData(info);
                                marqueeView.setMarqueeFactory(noticeMFView);
                                marqueeView.startFlipping();
                            }
                        } else {
                            DisPlay(parse.getString("message"));
                        }
                    } else {
                        DisPlay("网络异常！");
                    }
                }
            }
        });
    }

    public CharSequence formatStr(String title) {
        String left = title.substring(0, title.lastIndexOf("奖") + 1);
        String middle = title.substring(title.lastIndexOf("奖") + 1, title.lastIndexOf("元"));
        return Html.fromHtml(left + "<html><body><font color='red'>" + middle + "</font></body></html>元");
    }

    /**
     * 获取彩种
     */
    void getLottery() {

        UserBean userBean = PreferenceUtil.readUser(getActivity());
        String params = "";
        if (userBean != null) {
            params = "?user=" + userBean.getUsername();
        }

        HttpManager.getAsyn(Constant_Url.LOTTERY + params, new HttpManager.StringCallback() {
            @Override
            public void onFailure(Request request, IOException e) {
                MyLog.i(request.toString());
                if (sr_refresh != null)
                    sr_refresh.setRefreshing(false);
                initCacheMenu();
                DisPlay("网络异常！");
            }

            @Override
            public void onResponse(String response) {
                if (sr_refresh != null)
                    sr_refresh.setRefreshing(false);

                if (!TextUtils.isEmpty(response)) {

                    List<HomeItem> list = FastOk.getList(response, HomeItem.class);
                    if (list != null) {
                        if (list.size() > 0) {
                            mMenu.clear();
                            mMenu.addAll(list);
                            PreferenceUtil.setHomeMenu(getActivity(), mMenu);
                            gv.setMenu(mMenu);
                        } else {
                            initCacheMenu();
                        }
                    } else {
                        initCacheMenu();
                    }

                } else {
                    DisPlay("网络异常！");
                }
            }
        });
    }

    void initCacheMenu() {
        try {
            List<HomeItem> homeMenu = PreferenceUtil.getHomeMenu(getActivity());
            if (homeMenu != null && mMenu.size() <= 0) {
                mMenu.clear();
                mMenu.addAll(homeMenu);
                gv.setMenu(mMenu);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    void getBannerData() {
        HttpManager.getAsyn(Constant_Url.ADVERT_URL, new HttpManager.StringCallback() {
            @Override
            public void onFailure(Request request, IOException e) {
                MyLog.i(request.toString());
                if (sr_refresh != null)
                    sr_refresh.setRefreshing(false);
            }

            @Override
            public void onResponse(String response) {
                if (sr_refresh != null)
                    sr_refresh.setRefreshing(false);
                RecordsBean recordsBean = FastOk.get(response, RecordsBean.class);
                if (recordsBean == null) {
                    DisPlay("网络异常！");
                    return;
                }
                if (recordsBean.getRecords() == null) {
                    DisPlay("网络异常！");
                    return;
                }
                listData.clear();
                listData.addAll(recordsBean.getRecords());
                if (listData != null && listData.size() > 0) {
                    initBanner();
                }
            }
        });
    }

    private void initBanner() {
        if (viewflow == null) return;
        viewflow.setNestedpParent((ViewGroup) viewflow.getParent());
        viewflow.setAdapter(new BannerAdapter(getActivity(), listData).setInfiniteLoop(true));
        viewflow.setmSideBuffer(listData.size()); //实际图片张数，
        viewflowindic.setCount(listData.size());
        viewflow.setFlowIndicator(viewflowindic);
        viewflow.setTimeSpan(4500);
        viewflow.setSelection(listData.size() * 1000); // 设置初始位置
        viewflow.startAutoFlowTimer(); // 启动自动播放
    }

    void startAction(String type) {
       if (type.equals("pls") || type.equals("plw") || type.equals("sd") || type.equals("qxc")) {
            Intent intent = new Intent(getActivity(), BetPlS_PLW_SD_QXCActivity.class);
            intent.putExtra("type", type);
            startActivity(intent);
        }  else if (type.equals("sfc") || type.equals("rxj") || type.equals("rjc")) {
            Intent intent = new Intent(getActivity(), BetRXJ_SFCActivity.class);
            intent.putExtra("type", type);
            startActivity(intent);
        } else if (type.equals("cqssc")) {
            Intent intent = new Intent(getActivity(), BetSSCActivity.class);
            intent.putExtra("type", type);
            startActivity(intent);
        } else if (type.equals("jclq")) {
            BaseUtils.startAcy(getActivity(), LotteryJCLQActivity.class);
        } else if (type.equals("jczq")) {
            BaseUtils.startAcy(getActivity(), LotteryJCZQActivity.class);
        } else if (type.equals("gyj") || type.equals("gj")||type.equals("jcgj")) {
            Intent intent = new Intent(getActivity(), ChampionActivity.class);
            intent.putExtra("type", type);
            startActivity(intent);
        }
    }

    //中间四个按钮的点击事件；
    @OnClick({R.id.ll_sign, R.id.ll_lottery,
            R.id.ll_task, R.id.ll_activity,R.id.tv_right_option})
    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.ll_sign:
                //实现签到的跳转；
                checkLogin(new Callback() {
                    @Override
                    public void callbackSuccess() {
                        super.callbackSuccess();
                        startActivity(new Intent(getActivity(), SignActivity.class));
                    }
                });
                break;
            case R.id.ll_lottery:
                checkLogin(new Callback() {
                    @Override
                    public void callbackSuccess() {
                        super.callbackSuccess();
                        startActivity(new Intent(getActivity(), LuckyWalkActivity.class));
                    }
                });
                //实现抽奖的跳转；
                break;
            case R.id.ll_task:
                //实现任务的跳转
                startActivity(new Intent(getActivity(), TaskActivity.class));
                break;
            case R.id.ll_activity:
                //实现活动的跳转；
                startActivity(new Intent(getActivity(), EventActivity.class));
                break;
            case R.id.tv_right_option:
                //这里将启动开奖信息;
                startActivity(new Intent(getActivity(), LotteryInfoActivity.class));
                break;
        }
    }

    //这里是获取微信公众号的一个网络请求；
    public void getWeChat() {

        //这里我们先从本地获取公众号，如果本地没有公众号的话，我们就从服务器获取数据；
        String mpweixin = PreferenceUtil.readString(getActivity(), PreferenceUtil.WEXIN, "");
        if (!TextUtils.isEmpty(mpweixin)) {
            //这里表示获取到微信公众号了；
            gv.addFooter("<html>更多资讯请关注公众号:<font color=#d65f6e>" + mpweixin + "</font>" + "<font color=#cecece>(点击可复制)</font></html>");
            return;
        }

        String username=PreferenceUtil.getUserName(getActivity());
        String password=PreferenceUtil.getPassword(getActivity());

        HashMap<String, String> paramsMap = new HashMap<>();

        paramsMap.put("user",username);
        paramsMap.put("password",password);

        HttpManager.postAsyn(Constant_Url.CONFIG, new HttpManager.StringCallback() {
            @Override
            public void onFailure(Request request, IOException e) {

            }

            @Override
            public void onResponse(String response) {

                try {
                    JSONObject jsonObject = FastOk.get(response, JSONObject.class);
                    //微信公众号；
                    String mpweixin = jsonObject.getString("mpweixin");
                    String kuNumber = jsonObject.getString("kefu");
                    String qq = jsonObject.getString("qq");

                    //保存到本地；
                    PreferenceUtil.writeString(getActivity(), PreferenceUtil.KF_NUMBER, kuNumber);
                    PreferenceUtil.writeString(getActivity(), PreferenceUtil.WEXIN, mpweixin);
                    PreferenceUtil.writeString(getActivity(), PreferenceUtil.KF_QQ_NUMBER, qq);

                    if (!TextUtils.isEmpty(mpweixin)) {
                        // gv.addFooter(mpweixin);
                        gv.addFooter("<html>更多资讯请关注公众号:<font color=#d65f6e>" + mpweixin + "</font>" + "<font color=#cecece>(点击可复制)</font></html>");
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        },paramsMap);
        //gv.addFooter();
    }


}
